//
//  WBRfreshControl.swift
//  Weibo
//
//  Created by 李亚乐 on 15/12/15.
//  Copyright © 2015年 李亚乐. All rights reserved.
//

import UIKit

/// RefreshControl 偏移量
private let WBRefreshControlOffset: CGFloat = -60

// MARK: - 刷新控制
class WBRfreshControl: UIRefreshControl {
    
    /// 刷新控件
    private lazy var refreshView = WBRefreshView.loadRefreshView()
    
    /// 观察者
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if frame.origin.y > 0 {
            return
        }
        
        /// 播放动画
        if refreshing {
            refreshView.startAnimation()
        }
        
        /// 翻转箭头
        if frame.origin.y < WBRefreshControlOffset && !refreshView.isUp {
            refreshView.isUp = true
        } else if frame.origin.y > WBRefreshControlOffset && refreshView.isUp {
            refreshView.isUp = false
        }
        
    }
    
    override init() {
        super.init()
        //添加背景颜色 frame 值会改变
//        backgroundColor = UIColor.redColor()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    // MARK: - 设置 UI
    private func setupUI() {
        
        tintColor = UIColor.clearColor()
        //添加控件
        addSubview(refreshView)
        //设置布局
        refreshView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
            //XIB加载需要指定大小 size
            make.size.equalTo(refreshView.bounds.size)
        }
        
        //KVO
        //主线程异步添加观察者
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
        }
    }
    
    /// 移除观察者
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    /// 重写系统开始结束刷新方法
    override func beginRefreshing() {
        super.beginRefreshing()
        refreshView.startAnimation()
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopAnimation()
    }
}

//MARK: - 刷新视图
class WBRefreshView: UIView {
    /// 转圈图标
    @IBOutlet weak var loadingIconView: UIImageView!
    /// 箭头图标
    @IBOutlet weak var tipIconView: UIImageView!
    /// 正在刷新视图
    @IBOutlet weak var tipView: UIView!
    
    /// 箭头标记
    var isUp = false {
        didSet {
            rotateTipicon()
        }
    }

    /// 类方法加载刷新视图
    ///
    /// - returns:  自定义 RefreshView
    class func loadRefreshView() -> WBRefreshView {
        
        let nib = UINib(nibName: "WBRefreshView", bundle: nil)
        return nib.instantiateWithOwner(nil, options: nil)[0] as! WBRefreshView
    }
    
    /// 旋转箭头
    private func rotateTipicon() {
        
        var angle = CGFloat(M_PI)
        angle += isUp ? -0.0000001 : 0.0000001
        
        UIView.animateWithDuration(0.5) { () -> Void in
            self.tipIconView.transform = CGAffineTransformRotate(self.tipIconView.transform, CGFloat(angle))
        }
    }
    
    /// 开始转轮动画
    func startAnimation() {
        tipView.hidden = true
        
        let key = "transform.rotation"
        
        if loadingIconView.layer.animationForKey(key) != nil {
            return
        }
        let anim = CABasicAnimation(keyPath: key)
        
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 1
        anim.removedOnCompletion = false
        
        loadingIconView.layer.addAnimation(anim, forKey: key)
    }
    
    /// 结束转轮动画
    func stopAnimation() {
        tipView.hidden = false
        loadingIconView.layer.removeAllAnimations()
    }
    
}



